<template>
	<view class="currentPage" id="id">
		<navbar :title='receiverInfo.nickName || receiverInfo.registerMail ' :isBack='true'>
			<view class="friend" slot='opBtn'>
				<u-icon name="more-circle" size="48" @click="toUser"></u-icon>
			</view>
		</navbar>
		<view class="main">
			<view class="chat_area" id="chat-area">
				<button @click="loadMore">加载更多</button>
				<view class="chat_item" v-for="(item ,index) in chatList" :class="item.isSelf === 'y' ?'right' :'left'">
					<view class="msg" v-if="item.type ==='text'">{{item.content}}</view>
					<view class="image" v-if="item.type === 'image'">
						<image :src="item.content" mode="widthFix" @click="previewImage(index)">
							<!-- 		<u-loading slot="loading"></u-loading>
							<view slot="error" style="font-size: 24rpx;">加载失败</view> -->
						</image>
					</view>
					<view class="voice msg" v-if="item.type === 'voice'" hover-class="hoverClass" hover-stay-time='100'
						@click="playVoice(item)">语音</view>
					<view class="avatar">
						<image :src="userInfo.avatar" mode="" v-if="item.isSelf == 'y'"></image>
						<image :src="receiverInfo.avatar" mode="" v-else></image>
					</view>

				</view>
			</view>
			<view class="input" :style="{'bottom':bottom}">
				<view class="">
					<textarea ref="textarea" :style="{'height': height}" v-model="value" class="textarea"
						@linechange='linechange' :maxlength="500" @keyboardheightchange="keyboardheightchange"
						@keydown.enter="sendPrivateMsg"></textarea>
					<button type="primary" @tap='sendPrivateMsg' :disabled="value==''">发送</button>
				</view>
				<view class="tool_bar">
					<view class="item" v-for="(item,index) in tool" @tap='toolOp(index)'>
						<image :src="item.path" mode="aspectFit"></image>
					</view>
				</view>
			</view>
		</view>

		<u-popup v-model="show" class="u-popup" mode="bottom" height="500" duration="50" :mask='false' @close='close'>
			<view class="popup-content">
				<view class="tips">{{tipsText}}</view>
				<view class="press">
					<image src="/static/icon/chatUI/mkf_big.png" mode="" @longtap.stop.prevent="talk"
						@touchend='touchEnd'></image>
				</view>
			</view>
		</u-popup>
		<!-- <view class="chat_area"></view> -->
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	// #ifdef APP-PLUS
	const recorderManager = uni.getRecorderManager()
	// #endif
	import api from "../../api/index.js"
	// import $socket from '../../tool/socketCon.js'
	import navbarNvue from "@/components/navbarNvue.vue"
	export default {
		components: {
			navbarNvue
		},
		data() {
			return {
				tipsText: '按住说话',
				show: false,
				title: '',
				toId: "",
				height: '50rpx',
				bottom: '70rpx',
				value: '', //输入的信息
				chatList: [], //聊天列表
				sender: '', //发送人
				index: -1,
				tool: [{
						id: 1,
						path: '/static/icon/chatUI/image.png'
					}, {
						id: 2,
						path: '/static/icon/chatUI/maikefen.png'
					}, {
						id: 3,
						path: '/static/icon/chatUI/zxj.png'
					},
					{
						id: 4,
						path: '/static/icon/chatUI/bq.png'
					}
				],
				chatData: [],
				receiverInfo: {},
				chatImageList: [],
				pageIndex: 1,
				pageSize: 10
			};
		},
		computed: {
			...mapState(['userInfo', 'phoneInfo'])
		},
		onLoad(e) {
			console.log(e)
			this.queryInfo(e.receiverId).then(() => {
				this.loadChatMsg().then(res => {
					console.log('分页查询结果', res)
					res.forEach(ele => {
						this.chatList.unshift(ele)
					})
				})
			})
			this.checkConnect()
			//查询与此人的全部聊天记录
			// this.$opChatDB.selectSqlAll(this.$replaceTableNameLine(e.receiverId)).then(res => {
			// 	console.log('聊天记录', res)
			// 	if (res.code == 1) {
			// 		//拿到本地存储结果
			// 		let data = res.data
			// 		data.forEach(ele => {
			// 			ele.to = JSON.parse(ele.to)
			// 			ele.from = JSON.parse(ele.from)
			// 		})
			// 		this.chatList = data 
			// 	}
			// })

		},
		onUnload() {
			// uni.$off('privateMsg_SystemToUser')

		},
		watch: {
			pageIndex() {
				this.loadChatMsg().then(res => {
					console.log(res)
					res.forEach(ele => {
						this.chatList.unshift(ele)
					})
				})
			}
		},
		mounted() {
			uni.$on('privateMsg_SystemToUser', data => {
				console.log('PREVITECHAT页面接收私有消息', data)
				data.isSelf = 'n'
				this.chatList.push(data)
				this.$nextTick(() => {
					this.scrollPage()
				})
			})
			this.$nextTick(() => {
				this.scrollPage(0, 0)
			})
		},
		methods: {
			loadMore() {
				this.pageIndex++
			},
			loadChatMsg() {
				return this.$selectSql({
						name: 'chat',
						sql: `select * from "${this.$replaceTableNameLine(this.receiverInfo.id)}"  order by date desc limit ${this.pageSize} offset ${(this.pageIndex - 1)*this.pageSize}`
					})
					.then(res => {
						// console.log('分页查询结果', res)
						if (res.code == 1) {
							return res.data
							// resolve(res.data.reverse())
							//拿到本地存储结果
							// let data = res.data.reverse()
							// console.log('数组反转', data)
							// data.forEach(ele => {
							// 	ele.to = JSON.parse(ele.to)
							// 	ele.from = JSON.parse(ele.from)
							// })
							// this.chatList.concat(data)
							// this.$forceUpdate()
							// console.log(this.chatList)
						}
					})

			},
			toUser() {
				uni.navigateTo({
					url: `/pages/user_detail/user_detail?info=${JSON.stringify(this.receiverInfo)}&pRoomIn=1`
				})
			},
			playVoice(item) {
				// plus.io.resolveLocalFileSystemURL(base64,(e)=>{
				// 	console.log('成功',e)
				// },err=>{
				// 	console.log('失败',err)
				// })


				// let bstr = atob(base64)
				// let n = 
				if (item.isSelf === 'y') {
					let audio = uni.createInnerAudioContext()
					audio.src = item.content
					audio.onError(e => {
						console.log('错误', e)
					})
					audio.onCanplay(() => {
						audio.play()
					})
				} else {

				}
			},
			scrollPage(scroll = 0, d = 200) {
				const query = uni.createSelectorQuery().in(this);
				query.select('#chat-area').boundingClientRect(data => {
					console.log("得到布局位置信息", data);
					console.log("节点离页面顶部的距离为" + data.top);
					if (data.height > (this.phoneInfo.screenHeight - (100 / 2) + 5 - scroll)) {
						uni.pageScrollTo({
							scrollTop: Math.ceil(data.height) - scroll,
							duration: d
						})
					}

				}).exec();
			},
			checkConnect() {
				if (!(this.$socket && this.$socket.connected)) {
					console.log('$socket未连接', this.userInfo.id)
					this.$initSocket(this.userInfo.id)
					this.$socket.on('MSG_OK', () => {
						uni.showToast({
							title: '对方客户端已收到消息',
							icon: 'none'
						})
					})
				} else {
					this.$socket.on('MSG_OK', () => {
						uni.showToast({
							title: '对方客户端已收到消息',
							icon: 'none'
						})
					})
				}
			},
			queryInfo(receiverId) {
				return api.searchById({
					id: receiverId
				}).then(res => {
					console.log('对方信息', res)
					res.code === 1 ? this.receiverInfo = res.data : uni.showToast({
						title: res.msg,
						icon: 'none'
					})


				})
			},
			previewImage(index) {
				let imgs = {}
				let urls = []
				this.chatList.forEach((ele, index) => {
					if (ele.type === 'image') {
						imgs[index] = ele.content
						urls.push(ele.content)
					}
				})
				// let urls = this.chatImageList
				let indexOf = urls.indexOf(imgs[index])
				uni.previewImage({
					urls: urls,
					current: indexOf
				})

			},
			createTableAndQuery(tableName) {
				//数据库打开,尝试为当前聊天对象创建表
				this.$opChatDB.createTable(tableName).then(res => {
					console.log(res)
					if (res.code === 1) {
						//表存在或者已经创建，查询表全部数据
						this.$opChatDB.selectSqlAll(tableName).then(res => {
							console.log(res)
							if (res.code == 1) {
								//拿到本地存储结果
								let data = res.data
								data.forEach(ele => {
									ele.to = JSON.parse(ele.to)
									ele.from = JSON.parse(ele.from)
								})
								this.chatList = data
							}
						})

					}
				})
			},
			class_style(item) {
				console.log(item)
				if (item.isSelf === 'y') {
					return 'right'
				} else {
					return 'left'
				}


			},
			receiverFun(type, content) {
				if (!type || !content) {
					throw new Error('需提供type和content')
				}
				let chatObj = {
					to: {
						receiver: this.receiverInfo.registerMail, //接收者账号
						receiverId: this.receiverInfo.id //接收者id
					},
					from: {
						sender: this.userInfo.registerMail, //发送人账号
						senderId: this.userInfo.id //发送人id
					},
					type,
					content,
					date: new Date().getTime(),
					avatar: this.userInfo.avatar

				}
				return chatObj
			},
			//发送私有消息
			sendPrivateMsg() {
				let obj = this.receiverFun('text', this.value)
				console.log('obj', obj)
				console.log(this.$socket)
				this.$socket.emit('privateMsg_UserToSystem', obj)
				obj.isSelf = 'y'
				this.chatList.push(obj)
				this.$nextTick(() => {
					this.scrollPage()
				})
				console.log(this.chatList)
				//将发送的消息存储
				// #ifdef APP-PLUS
				this.$opChatDB.addData(this.$replaceTableNameLine(this.receiverInfo.id), obj).then(res => {
					console.log('保存结果', res)
				})
				// #endif
				this.value = ""

			},
			close() {
				this.bottom = '70rpx'
			},
			//松开
			touchEnd() {
				recorderManager.stop()
				recorderManager.onStop(e => {
					console.log('地址', e)
					let obj = this.receiverFun('voice', e.tempFilePath)
					obj.isSelf = 'y'
					this.chatList.push(obj)
					// #ifdef APP-PLUS
					this.$opChatDB.addData(this.$replaceTableNameLine(this.receiverInfo.id), obj).then(res => {
						console.log('保存结果', res)
					})
					// #endif
					this.handleVoice(e.tempFilePath).then(base64 => {
						let obj = this.receiverFun('voice', base64)

						this.$socket.emit('privateMsg_UserToSystem', obj)

						// console.log(obj)

					})

				})
				this.tipsText = '按住说话'
			},
			handleVoice(voicePath) {
				return new Promise((resolve, reject) => {
					plus.io.requestFileSystem(plus.io.PRIVATE_DOC, fs => {
						var reader = null;
						fs.root.getFile(voicePath, {},
							entry => {
								entry.file(file => {
										console.log(file)
										reader = new plus.io.FileReader();
										reader.readAsDataURL(file);
										reader.onloadend = (e) => {
											resolve(e.target.result)
										};
									},
									function(e) {
										alert(e.message);
									});
							});
					});
				})
			},
			//长按开始录音
			talk() {
				this.tipsText = '正在录音，松开手指停止'
				recorderManager.start()
			},
			toolOp(index) {
				//发送图片
				if (index == 0) {
					uni.chooseImage({
						sourceType: ['album'],
						count: 9,
						success: (res) => {
							console.log(res)
							// #ifdef H5
							res.tempFiles.forEach(ele => {
								uniCloud.uploadFile({
									filePath: ele.path,
									cloudPath: `${ele.name}.${ele.type.split('/')[1]}`,
									success: (e) => {
										this.$api.saveImgId({
											imgId: e.fileID
										}).then(res => {
											console.log('保存', res)
										})
										let obj = this.receiverFun('image', e.fileID)
										this.$socket.emit('privateMsg_UserToSystem', obj)
										obj.isSelf = 'y'
										this.chatList.push(obj)
										// #ifdef APP-PLUS
										this.$opChatDB.addData(this.$replaceTableNameLine(
											this.receiverInfo.id), obj).then(res => {
											console.log('保存结果', res)
										})
										// #endif
										this.$nextTick(() => {
											this.scrollPage()
										})
										console.log(this.chatList)
									},
									fail(err) {
										console.log('上传失败', err)
									}
								});
							})
							// #endif
							// #ifdef APP-PLUS
							res.tempFilePaths.forEach((ele, index) => {
								uni.compressImage({
									src: res.tempFilePaths[index],
									quality: 70,
									success: (res) => {
										console.log(res)
										uniCloud.uploadFile({
											filePath: res.tempFilePath,
											cloudPath: `${ele.name}.${res.tempFilePath.split('.')[res.tempFilePath.split('.').length - 1]}`,
											success: (e) => {
												console.log(e)
												let obj = this.receiverFun(
													'image', e.fileID)
												this.$socket.emit(
													'privateMsg_UserToSystem',
													obj)
												obj.isSelf = 'y'
												this.chatList.push(obj)
												// #ifdef APP-PLUS
												this.$opChatDB.addData(this
													.$replaceTableNameLine(
														this.receiverInfo
														.id), obj).then(
													res => {
														console.log('保存结果',
															res)
													})
												// #endif
												this.$nextTick(() => {
													this.scrollPage()
												})
												console.log(this.chatList)
											},
											fail(err) {
												console.log('上传失败', err)
											}
										});
									}
								})
							})
							// #endif
						},
						fail: (err) => {

						}
					})
				}
				//打开录音界面
				if (index == 1) {
					this.scrollPage(568 / 2)
					this.show = true
					this.bottom = '568rpx'

				}
			},
			linechange(e) {
				console.log(e)
				if (e.detail.heightRpx > 378) {
					return
				}
				this.height = e.detail.heightRpx + 'rpx'
				console.log(parseInt(this.height))
			},
			keyboardheightchange(e) {
				console.log(e)
				if (e.target.height < 100) {
					this.bottom = '70rpx'
					this.$nextTick(() => {
						this.scrollPage()
					})
					return
				}
				this.bottom = e.target.height - this.height + 'rpx'
				this.scrollPage(e.target.height)

			}
		}
	}
</script>

<style lang="scss" scoped>
	.currentPage {
		// background-color: rgb(234, 237, 244);
	}

	.friend {
		position: absolute;
		right: 15rpx;
		bottom: 10rpx;

		/*  */
		image {
			width: 50rpx;
			height: 50rpx;
		}

	}

	.main {
		width: 92%;
		min-height: calc(100vh - 300rpx);
		// border: 1px solid;
		margin: 0 auto;
		padding-bottom: 200rpx;
	}

	.input {

		position: fixed;
		transition: bottom .1s linear;
		// bottom: 70rpx;
		// border: 1px solid;
		min-height: 50rpx;
		right: 0;
		left: 0;
		background-color: rgb(240, 240, 240);
		padding: 15rpx 20rpx;
		display: flex;

		// align-items: center;
		textarea {
			width: 550rpx;
			// padding: 15rpx;
			min-height: 50rpx;
			padding: 10rpx;
			// border: 1px solid red;
			border-radius: 25rpx;
			background-color: #FFFFFF;
			// border

		}

		button {
			height: 68rpx;
			position: absolute;
			bottom: 16rpx;
			right: 20rpx;
			font-size: 28rpx;
			background-image: $bgImage;
			color: #666;
		}
	}

	.tool_bar {
		height: 70rpx;
		width: 100%;
		// border: 1px solid;
		display: flex;
		position: absolute;
		bottom: -70rpx;
		right: 0;
		left: 0;
		justify-content: space-around;
		align-items: center;
		background-color: rgb(240, 240, 240);

		.item {
			image {
				height: 40rpx;
				width: 40rpx;
			}
		}
	}

	.popup-content {
		// border: 1px solid;
		text-align: center;

		.tips {
			margin: 50rpx;
			font-size: 30rpx;
		}

		.press {
			image {
				height: 200rpx;
				width: 200rpx;
				border-radius: 50%;
				box-shadow: 0 0 12px rgba(0, 0, 0, .6);
			}
		}
	}

	.chat_area {
		// border: 1px solid;
		// min-height: calc(100vh - 300rpx);

		.chat_item {
			// border: 1px solid;
			min-height: 80rpx;
			word-wrap: break-word;
			word-break: break-all;
			display: flex;
			position: relative;
			justify-items: center;
			margin: 30rpx 0;
			line-height: 80rpx;

			.msg {
				max-width: 71%;
				padding: 0 20rpx;
				border-radius: 25rpx;
				box-shadow: 0 0 1px rgba(128, 128, 128, .5);
			}

			image {
				width: 300rpx;
				border-radius: 25rpx;
				// border: 1px solid blue;
			}

			.voice {
				width: 200rpx;
			}

			.avatar {
				// border: 1px solid;
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				position: absolute;
				overflow: hidden;

				image {
					width: 80rpx;
					height: 80rpx;
				}
			}
		}

		.right {
			flex-direction: row-reverse;
			position: relative;
			// border: 1px solid red;

			.msg {

				margin-right: 120rpx;
				background: rgb(161, 216, 253);

			}

			.image {
				margin-right: 120rpx;
			}
		}

		.left {
			position: relative;

			.msg {
				margin-left: 120rpx;
				background: #ffff;
			}

			.avatar {
				// border: 1px solid;
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				position: absolute;

			}

			.image {
				margin-left: 120rpx;
			}
		}
	}

	.hoverClass {
		opacity: .2;
	}
</style>
